package cn.lyq.card.ui.wallet

import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.RecyclerView
import cn.lyq.card.R
import cn.lyq.card.base.BaseActivity
import cn.lyq.card.data.model.WalletInfo
import cn.lyq.card.data.src.Status
import cn.lyq.card.global.BusTag
import cn.lyq.card.manager.UserManager
import cn.lyq.card.ui.bank.BankCardActivity
import cn.lyq.card.ui.result.ResultActivity
import cn.lyq.card.utils.setClick
import cn.lyq.card.utils.toBankNo
import com.blankj.utilcode.util.BusUtils
import com.blankj.utilcode.util.SpanUtils
import com.blankj.utilcode.util.ToastUtils
import com.youth.banner.Banner
import com.youth.banner.adapter.BannerAdapter
import com.youth.banner.indicator.CircleIndicator
import kotlinx.android.synthetic.main.act_cash_msg.*
import kotlinx.android.synthetic.main.act_cash_msg.etCashMoney
import kotlinx.android.synthetic.main.act_cash_msg.tvCardName
import kotlinx.android.synthetic.main.act_cash_msg.tvCardNo
import kotlinx.android.synthetic.main.act_cash_msg.tvCashTip
import kotlinx.android.synthetic.main.act_cash_msg.tvChangeCard
import kotlinx.android.synthetic.main.act_cash_msg.tvConfirm
import kotlinx.android.synthetic.main.act_cash_msg_temp.*
import kotlinx.android.synthetic.main.layout_title.*


class CashMsgActivity : BaseActivity() {

    companion object {
        private const val KEY_INFO = "INFO"

        @JvmStatic
        fun start(context: Context, info: WalletInfo?) {
            val starter = Intent(context, CashMsgActivity::class.java)
                .putExtra(KEY_INFO, info)
            context.startActivity(starter)
        }
    }

    private val mModel by lazy {
        getVM(WalletVM::class.java)
    }
    private val mBanner by lazy {
        findViewById<Banner<String, BAdapter>>(R.id.banner)
    }
    private var mInfo: WalletInfo? = null

    override fun getLayoutId(): Int {
        return R.layout.act_cash_msg
    }

    override fun initView() {
        super.initView()
        mInfo = intent.getSerializableExtra(KEY_INFO)
            ?.takeIf { it is WalletInfo }
            ?.run { this as WalletInfo }

        setMyTitle(R.string.str_cash_quickly)
        tvTitleRight.setTextColor(ContextCompat.getColor(this, R.color.font_main))
        tvTitleRight.setText(R.string.str_cash_record)
        tvTitleRight.visibility = View.VISIBLE

        tvCardNo.text = UserManager.bankCardInfo?.cardNumber?.toBankNo() ?: ""
        tvCardName.text = UserManager.instance.value?.trueName ?: ""

        val golden = ContextCompat.getColor(this, R.color.font_golden)
        SpanUtils.with(tvCashTip)
            .append("提现时间")
            .append("T+0").setForegroundColor(golden)
            .append("，提现手续费为")
            .append("${mInfo?.serviceCharge ?: 0}元/笔").setForegroundColor(golden)
            .append("，税点为")
            .append("${mInfo?.taxPoint ?: 0.00}%").setForegroundColor(golden)
            .create()
        setBanner()
    }

    private fun setBanner() {
        mBanner.setDatas(mutableListOf())
        mBanner.addBannerLifecycleObserver(this)
        mInfo?.let {
            mBanner.adapter = BAdapter(this, it, mutableListOf("", "", ""))
        }
        mBanner.indicator = CircleIndicator(this)
        mBanner.setBannerGalleryEffect(8, 8, 12, 1f)
        mBanner.isAutoLoop(false)
    }

    override fun initListener() {
        super.initListener()
        tvConfirm.setClick {
            if (UserManager.instance.value?.hasCashPwd() == true) {
                val money = etCashMoney.text.trim().toString().toDoubleOrNull()
                if (money == null) {
                    ToastUtils.showShort(etCashMoney.hint)
                    return@setClick
                }
                val canCashMoney = getCashMoney()
                if (canCashMoney < money) {
                    ToastUtils.showShort(R.string.str_no_enough_cash)
                    return@setClick
                }
                setBarColor(true)
                CashPwdFg.newInstance(money, banner.currentItem).show(this)
            } else {
                setBarColor(true)
                CashPwdUnsetFg().show(this)
            }
        }
        tvTitleRight.setClick {
            startActivity(CashRecordActivity::class.java)
        }
        tvChangeCard.setClick {
            startActivity(BankCardActivity::class.java)
        }
    }

    private fun getCashMoney(): Double {
        return when (banner.currentItem) {
            1 -> mInfo?.personalBalance?.toDoubleOrNull() ?: 0.0
            2 -> mInfo?.cashBackBalance?.toDoubleOrNull() ?: 0.0
            3 -> mInfo?.subsidyBalance?.toDoubleOrNull() ?: 0.0
            else -> 0.0
        }
    }

    class BAdapter(val context: Context, val info: WalletInfo, data: MutableList<String>?) :
        BannerAdapter<String, BAdapter.Holder>(data) {

        private val bgRes = arrayOf(R.drawable.ic_blue, R.drawable.ic_orange, R.drawable.ic_red)
        private val typeRes = arrayOf(
            R.string.str_share_cash_amount,
            R.string.str_return_cash_amount,
            R.string.str_subsidy_cash_amount
        )

        override fun onCreateHolder(parent: ViewGroup?, viewType: Int): Holder {
            return Holder(
                LayoutInflater.from(context).inflate(R.layout.item_cash_msg, parent, false)
            )
        }

        override fun onBindView(holder: Holder, data: String?, position: Int, size: Int) {
            when (position % 3) {
                0 -> {
                    holder.tvValue.text = info.personalBalance ?: "0.00"
                    holder.tvAmount.text = "累计收益：${info.personalProfit ?: "0.00"}"
                }
                1 -> {
                    holder.tvValue.text = info.cashBackBalance ?: "0.00"
                    holder.tvAmount.text = "累计收益：${info.cashBackProfit ?: "0.00"}"
                }
                2 -> {
                    holder.tvValue.text = info.subsidyBalance ?: "0.00"
                    holder.tvAmount.text = "累计收益：${info.subsidyProfit ?: "0.00"}"
                }
            }
            holder.bg.setBackgroundResource(bgRes[position % 3])
            holder.tvType.setText(typeRes[position % 3])
        }

        class Holder(view: View) : RecyclerView.ViewHolder(view) {
            val bg: TextView = view.findViewById(R.id.bg)
            val tvType: TextView = view.findViewById(R.id.tvType)
            val tvValue: TextView = view.findViewById(R.id.tvValue)
            val tvAmount: TextView = view.findViewById(R.id.tvAmount)
        }
    }

    private fun getWalletInfo() {
        mModel.getWalletInfo().observe(this, Observer {
            when (it?.status) {
                Status.LOADING -> {
                }
                Status.ERROR -> {
                    ToastUtils.showShort(it.message.getMsg())
                }
                Status.SUCCESS -> {
                    it.data?.run {
                        mInfo = this
                        setBanner()
                    }
                }
            }
        })
    }

    @BusUtils.Bus(tag = BusTag.CASH_APPLY, threadMode = BusUtils.ThreadMode.MAIN)
    fun actionApplyCash(param: Triple<Double, String, Int>) {
        mModel.applyCash(param.first, param.second, param.third).observe(this, Observer {
            when (it?.status) {
                Status.LOADING -> showLoading()
                Status.SUCCESS -> {
                    BusUtils.post(BusTag.REFRESH_BALANCE)
                    getWalletInfo()
                    ResultActivity.start(this, 4)
                    dismissLoading()
                }
                Status.ERROR -> {
                    dismissLoading()
                    ToastUtils.showShort(it.message.getMsg())
                }
            }
        })
    }
}